<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>五子棋对战 - 游戏大厅</title>
    <link rel="stylesheet" href="./css/common.css">
    <link rel="stylesheet" href="./css/game_hall.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <div class="nav">
        <div class="logo">
            <i class="fas fa-chess-board"></i>
            <span>五子棋对战平台</span>
        </div>
        <div id="user-greeting"></div>
    </div>

    <div class="container">
        <div class="card hall-container">
            <div class="user-info">
                <h3><i class="fas fa-user"></i> 个人信息</h3>
                <div class="user-stats">
                    <div class="stat-item">
                        <div class="stat-value" id="score">0</div>
                        <div class="stat-label">积分</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="total-count">0</div>
                        <div class="stat-label">总场次</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value" id="win-count">0</div>
                        <div class="stat-label">获胜场次</div>
                    </div>
                </div>
            </div>

            <div class="match-section">
                <div class="status-message" id="screen">准备就绪，点击开始匹配</div>
                <div id="match-button">开始匹配</div>
            </div>
        </div>
    </div>

    <!-- 错误提示弹窗 -->
    <div class="custom-modal" id="errorModal">
        <div class="modal-content">
            <div id="error-content"></div>
            <button class="btn btn-primary" onclick="document.getElementById('errorModal').style.display='none'">确定</button>
        </div>
    </div>

    <script src="./js/jquery.min.js"></script>
    <script>
        var ws_url = "ws://" + location.host + "/hall";
        var ws_hdl = null;
        var button_flag = "stop"; // stop-未匹配，start-匹配中
        var reconnect_count = 0;
        var username = "";

        // 页面卸载时关闭连接
        window.onbeforeunload = function() {
            if (ws_hdl && ws_hdl.readyState === WebSocket.OPEN) {
                ws_hdl.close();
            }
        }

        // 错误提示
        function showError(msg) {
            const modal = document.getElementById("errorModal");
            document.getElementById("error-content").textContent = msg;
            modal.style.display = "flex";
        }

        // 初始化WebSocket
        function init_ws_handlers() {
            ws_hdl.onopen = ws_onopen;
            ws_hdl.onclose = ws_onclose;
            ws_hdl.onerror = ws_onerror;
            ws_hdl.onmessage = ws_onmessage;
        }

        // 获取用户信息
        function get_user_info() {
            $.ajax({
                url: "/info",
                type: "get",
                success: function(res) {
                    if (!res || typeof res !== "object") {
                        showError("获取用户信息失败");
                        redirectToLogin();
                        return;
                    }

                    if (!res.username || res.score === undefined) {
                        showError("用户信息不完整");
                        redirectToLogin();
                        return;
                    }

                    // 更新用户信息显示
                    username = res.username;
                    document.getElementById("user-greeting").textContent = `欢迎，${username}`;
                    document.getElementById("score").textContent = res.score;
                    document.getElementById("total-count").textContent = res.total_count || 0;
                    document.getElementById("win-count").textContent = res.win_count || 0;

                    // 初始化WebSocket
                    ws_hdl = new WebSocket(ws_url);
                    init_ws_handlers();
                },
                error: function(xhr) {
                    showError("获取用户信息失败，请重新登录");
                    redirectToLogin();
                }
            });
        }

        // 跳转登录页
        function redirectToLogin() {
            setTimeout(() => {
                location.replace("/login.html");
            }, 1500);
        }

        // 初始化匹配按钮事件
        function init_button_event() {
            const be = document.getElementById("match-button");
            be.onclick = function() {
                if (!ws_hdl || ws_hdl.readyState !== WebSocket.OPEN) {
                    showError("连接未就绪，请稍后重试！");
                    return;
                }

                if (button_flag === "stop") {
                    // 开始匹配
                    ws_hdl.send(JSON.stringify({ optype: "match_start" }));
                    button_flag = "start";
                    be.innerHTML = "匹配中...点击停止";
                    be.classList.add("loading");
                    document.getElementById("screen").textContent = "正在寻找对手...";
                } else {
                    // 停止匹配
                    ws_hdl.send(JSON.stringify({ optype: "match_stop" }));
                    button_flag = "stop";
                    be.innerHTML = "开始匹配";
                    be.classList.remove("loading");
                    document.getElementById("screen").textContent = "已取消匹配";
                }
            }
        }

        // WebSocket回调函数
        function ws_onopen() {
            console.log("websocket 连接成功");
            document.getElementById("screen").textContent = "连接成功，点击开始匹配";
        }

        function ws_onclose() {
            console.log("websocket 连接关闭");
            if (button_flag === "start") {
                button_flag = "stop";
                const be = document.getElementById("match-button");
                be.innerHTML = "开始匹配";
                be.classList.remove("loading");
                document.getElementById("screen").textContent = "连接已断开";
            }
        }

        function ws_onerror() {
            console.log("websocket 连接失败，尝试重连...");
            reconnect_count++;
            if (reconnect_count <= 3) {
                setTimeout(() => {
                    ws_hdl = new WebSocket(ws_url);
                    init_ws_handlers();
                }, 2000);
            } else {
                showError("网络异常，无法连接游戏大厅，请刷新页面重试！");
                reconnect_count = 0;
            }
        }

        function ws_onmessage(evt) {
            try {
                const resp = JSON.parse(evt.data);
                switch (resp.optype) {
                    case "match_success":
                        showError("对战匹配成功，即将进入游戏房间！", true);
                        setTimeout(() => {
                            window.location.assign("/game_room.html");
                        }, 1000);
                        break;
                    case "match_start":
                        if (resp.result) {
                            console.log("加入匹配队列成功");
                            document.getElementById("screen").textContent = "匹配中...请等待";
                        } else {
                            showError("加入匹配队列失败：" + (resp.reason || "未知错误"));
                            button_flag = "stop";
                            const be = document.getElementById("match-button");
                            be.innerHTML = "开始匹配";
                            be.classList.remove("loading");
                        }
                        break;
                    case "match_stop":
                        if (resp.result) {
                            console.log("退出匹配队列成功");
                            button_flag = "stop";
                            const be = document.getElementById("match-button");
                            be.innerHTML = "开始匹配";
                            be.classList.remove("loading");
                            document.getElementById("screen").textContent = "已退出匹配队列";
                        } else {
                            showError("退出匹配队列失败：" + (resp.reason || "未知错误"));
                        }
                        break;
                    case "hall_ready":
                        if (!resp.result) {
                            showError("进入大厅失败：" + (resp.reason || "未知错误"));
                            redirectToLogin();
                        }
                        break;
                    default:
                        showError("收到未知消息：" + JSON.stringify(resp));
                }
            } catch (e) {
                showError("消息解析失败：" + e.message);
                console.error("消息解析异常：", evt.data, e);
            }
        }

        // 页面加载完成后初始化
        document.addEventListener("DOMContentLoaded", function() {
            get_user_info();
            init_button_event();
        });
    </script>
</body>
</html>